package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.DictionaryForm;
import com.springboot.cloud.demos.entity.po.Dictionary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class DictionaryService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "queryFallback")
    public Result<List<Dictionary>> query(String keyNo) {
        return restTemplate.getForEntity("http://producer/dictionary/query?keyNo={1}", Result.class, keyNo).getBody();
    }

    public Result queryFallback(String keyNo) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result saveFallback(DictionaryForm dictionaryForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }


    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody DictionaryForm form) {
        return restTemplate.postForEntity("http://producer/dictionary", form, Result.class).getBody();
    }

    @SentinelResource(fallback = "queryFallback")
    public Result get(String id) {
        return restTemplate.getForEntity("http://producer/dictionary/{id}", Result.class, id).getBody();
    }

    @SentinelResource(fallback = "queryFallback")
    public Result<List<Dictionary>> list() {
        return restTemplate.getForEntity("http://producer/dictionary/list", Result.class).getBody();

    }
}
